<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { RowType } from '#/views/system/dict/dictItem/dictItem.data';

import { nextTick, ref } from 'vue';

import { useVbenDrawer, useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  dictItemDelApi,
  dictItemQueryPageListApi,
} from '#/api/system/dictItem';
import { useDictionaries } from '#/utils';

import DictItemFormModal from './modules/DictItemFormModal.vue';

const { translateValue } = useDictionaries(['status']);

const record = ref({});

const [Drawer, drawerApi] = useVbenDrawer({
  title: '字典配置',
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = drawerApi.getData<Record<string, any>>();
      drawerApi.setState({
        title: `字典配置「${record.value.dictCode}_${record.value.dictName}」`,
      });
      initFun({ dictId: record.value.id });
    }
  },
});

const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2',
  showCollapseButton: false,
  commonConfig: {
    colon: true,
    labelWidth: 80,
  },
  schema: [
    {
      component: 'Input',
      fieldName: 'itemText',
      label: '字典项文本',
      componentProps: {
        placeholder: '请输入字典项文本',
      },
    },
    // {
    //   component: 'ApiSelect',
    //   componentProps: {
    //     afterFetch: (data) => {
    //       return data.map((item: any) => ({
    //         label: item.itemText,
    //         value: item.itemVal,
    //       }));
    //     },
    //     api: getDictOptionsApi,
    //     params: {
    //       dictCode: 'status',
    //     },
    //     placeholder: '请选择状态',
    //     allowClear: true,
    //   },
    //   fieldName: 'status',
    //   label: '状态',
    // },
  ],
  // 自定义表单重置方法
  handleReset: () => {
    // eslint-disable-next-line no-use-before-define
    gridApi.formApi.resetForm();
    // eslint-disable-next-line no-use-before-define
    gridApi.query({ dictId: record.value.id });
  },
  // 自定义表单提交方法
  handleSubmit: (values) => {
    values = { ...values, dictId: record.value.id };
    // eslint-disable-next-line no-use-before-define
    gridApi.query(values);
  },
};

const gridOptions: VxeGridProps<RowType> = {
  height: 'auto',
  toolbarConfig: {
    slots: {
      buttons: 'toolbar-buttons',
    },
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    {
      title: '字典项文本',
      slots: { default: 'itemText' },
      field: 'itemText',
    },
    { title: '字典项值', field: 'itemVal', width: 80 },
    { title: '排序', field: 'sortRank', width: 50 },
    {
      title: '状态',
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'status',
          translateValue,
        },
      },
      field: 'status',
    },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page }, formValues) => {
        return await dictItemQueryPageListApi({
          pageNo: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
};
const [GridItem, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
const [DictItemFromModal, modalApi] = useVbenModal({
  connectedComponent: DictItemFormModal,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      gridApi.query({ dictId: record.value.id });
    }
  },
});

async function initFun(params) {
  // 等待 DOM 更新
  await nextTick();
  try {
    await gridApi.query(params);
  } catch {
    message.error('数据加载失败!');
  }
}
function openForm(type, id) {
  if (type === 0) {
    modalApi.setData({
      dictId: record.value.id,
    });
    modalApi.open();
  } else {
    modalApi.setData({
      id,
    });
    modalApi.open();
  }
}
async function delRow(row) {
  const msg = await dictItemDelApi(row.id);
  message.success(msg);
  await gridApi.query();
}
</script>

<template>
  <Drawer>
    <DictItemFromModal class="w-[40%]" />
    <GridItem>
      <template #toolbar-buttons>
        <a-button
          v-access:code="'sys:dictItem:add'"
          type="primary"
          @click="openForm(0)"
        >
          新增
        </a-button>
      </template>
      <template #itemText="{ row }">
        <template v-if="row.showStyle === 0">
          {{ row.itemText }}
        </template>
        <template v-else-if="row.showStyle === 1 && row.showStyleColor">
          <a-badge :status="row.showStyleColor" :text="row.itemText" />
        </template>
        <template v-else-if="row.showStyle === 2 && row.showStyleColor">
          <a-tag :color="row.showStyleColor">{{ row.itemText }}</a-tag>
        </template>
      </template>
      <template #action="{ row }">
        <a-button
          v-access:code="'sys:dictItem:edit'"
          size="small"
          type="link"
          @click="openForm(1, row.id)"
        >
          编辑
        </a-button>
        <a-popconfirm
          cancel-text="再想想"
          title="您确定要删除吗?"
          @confirm="delRow(row)"
        >
          <a-button
            v-access:code="'sys:dictItem:del'"
            size="small"
            type="link"
            danger
          >
            删除
          </a-button>
        </a-popconfirm>
      </template>
    </GridItem>
  </Drawer>
</template>
